﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UI.ParentForm;
using UI.Lib.Factory;
using System.Collections;
using UI.Lib;
using Components;
using Controls;

namespace UI.CommonForm
{
    public partial class FrmProductSelect : BaseTMain
    {
        private ToolStripButton tspF9 = null;
        private ToolStripButton tspAll = null;
        private ToolStripButton tspUnAll = null;
        private ToolStripButton tspF = null;
        private ToolStripButton tspSave = null;

        DataGridViewCellStyle selectedStyle = new DataGridViewCellStyle();
        DataGridViewCellStyle nomalStyle = new DataGridViewCellStyle();
        private bool isMutiSelect = false;
        private Hashtable table = null;
        private bool _isSelected = false;
        public bool IsSelected
        {
            get { return _isSelected; }
        }

        List<Hashtable> tbList = null;

        public bool IsMutiSelect
        {
            get { return isMutiSelect; }
            set { isMutiSelect = value; }
        }

        public FrmProductSelect(string _popKey, Hashtable _table, string word)
            : base(_popKey, "")
        {
            InitializeComponent();
            this.table = _table;

            this.Location = new Point(300, 300);

            this.txtInput.Text = word;
            selectedStyle.BackColor = Color.FromArgb(117, 149, 236);
            selectedStyle.Font = new Font(this.dgvMain.DefaultCellStyle.Font, FontStyle.Italic);
            nomalStyle = this.dgvMain.DefaultCellStyle;

            ClearTreeSelect(false);
        }

        #region 绑定左边树

        /// <summary>
        /// 加载树
        /// </summary>
        protected override void LoadTree()
        {
            Hashtable hs = new Hashtable();
            hs["muser"] = Context.Comocde + '%';

            DataTable areas = CommonHelper.Entity.ExecFun("getleverlist", hs);
            if (areas == null || 0 == areas.Rows.Count) return;

            this.treeMain.Nodes.Clear(); //先清空节点

            DataView dtView = new DataView(areas);
            dtView.RowFilter = string.Format("plevercode IS NULL or plevercode = ''");
            //绑定更节点
            TreeNode nodeFather = null;
            string levercode;
            for (int i = 0; i < dtView.Count; i++)
            {
                levercode = dtView[i]["levercode"].ToString();
                nodeFather = new TreeNode(levercode + "_" + dtView[i]["levername"].ToString());
                nodeFather.Name = dtView[i]["listid"].ToString();

                //该节点有子节点
                if (Validation.ToString(dtView[i]["haschild"]) == "1")
                    LoadChildNode(areas, nodeFather, Validation.ToString(dtView[i]["listid"]));

                this.treeMain.Nodes.Add(nodeFather);
            }

            this.treeMain.ExpandAll(); //展开所有
        }

        //加载子节点
        private void LoadChildNode(DataTable dtps, TreeNode nodeFather, string plistid)
        {
            TreeNode node = null;

            DataView dtView = new DataView(dtps);
            dtView.RowFilter = string.Format("plevercode = '{0}'", plistid);
            string levercode;
            for (int i = 0; i < dtView.Count; i++)
            {
                levercode = dtView[i]["levercode"].ToString();
                node = new TreeNode(levercode + "_" + dtView[i]["levername"].ToString());
                node.Name = dtView[i]["listid"].ToString();

                //该节点有子节点
                if (Validation.ToString(dtView[i]["haschild"]) == "1")
                    LoadChildNode(dtps, node, Validation.ToString(dtView[i]["listid"]));

                nodeFather.Nodes.Add(node);
            }
        }

        #endregion

        protected override void LoadGridLayout()
        {
            base.pageKey = this.ModuleCode;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.Size = new Size(900, 550);
            AddChildToolButton();
        }

        protected override void AutoSize()
        {
            this.scntMain.Dock = DockStyle.None;
            //this.dgvMain.Dock = DockStyle.None;
            int controlBoxHeight = 30;

            this.scntMain.Location = new Point(0, controlBoxHeight);
            this.scntMain.Size = new Size(this.Width, this.Height - controlBoxHeight);
            this.sitemMain.Width = this.dgvMain.Width = this.winpg.Width = this.scntMain.Panel2.Width;

            this.tspTop.Location = new Point(0, 0);
            this.tspTop.Size = new Size(this.scntMain.Panel2.Width, this.tspTop.Height);

            this.dgvMain.Location = new Point(0, this.tspTop.Height);
            this.dgvMain.Size = new Size(this.scntMain.Panel2.Width - 4, this.scntMain.Panel2.Height - this.tspTop.Height - this.winpg.Height - 4);

            this.winpg.Size = new Size(this.dgvMain.Width, this.winpg.Height);
        }

        private void treeMain_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (null == e.Node) return;

            classTmpWhere = string.Format("pvlistid ='{0}'", e.Node.Name);

            BindGrid();
        }

        protected override void UpdatePager(UI.Common.Pager pager)
        {
            pager.PageSize = 50; //每次提取50条一页
            //pager.FilterAppName = "muser";
            pager.StrWhere = "status <> '4'"
                + (string.IsNullOrEmpty(classTmpWhere) ? "" : (" AND " + classTmpWhere));

            if (null != table)
            {
                if (table.ContainsKey("table"))
                    pager.TableName = Validation.ToString(table["table"]);
                if (table.ContainsKey("strwhere"))
                    pager.StrWhere += " AND " + Validation.ToString(table["strwhere"]);
                //暂时就加这两个
            }
        }

        private void AddChildToolButton()
        {
            this.tspTop.Items.Add(tspF9 = base.CreateToolBtn("C", "忽略分类(F9)",
            new EventHandler(
                delegate
                {
                    ClearTreeSelect(true);
                })));

            this.tspTop.Items.Add(tspAll = base.CreateToolBtn("M", "全选(F10)",
            new EventHandler(
                delegate
                {
                    ChooseRow(true);
                })));

            this.tspTop.Items.Add(tspUnAll = base.CreateToolBtn("N", "取消(F11)",
                new EventHandler(
                    delegate
                    {
                        ChooseRow(false);
                    })));

            this.tspTop.Items.Add(tspF = base.CreateToolBtn("L", "反选(F12)",
            new EventHandler(
                delegate
                {
                    ChooseRow(null);
                })));


            this.tspTop.Items.Add(tspSave = base.CreateToolBtn("O", "确定(F5)",
            new EventHandler(
                delegate
                {
                    SaveData();
                })));

        }

        protected virtual void SaveData()
        {
            Hashtable tb = null;
            Dictionary<string, string> refCols = null;
            _isSelected = true;

            foreach (DataGridViewRow row in this.dgvMain.Rows)
            {
                if (Validation.IsNull(row.Tag)) continue; //未选中

                if (null == refCols)
                {
                    refCols = new Dictionary<string, string>();
                    foreach (PsDataGridViewTextBoxColumn col in this.dgvMain.Columns)
                    {
                        if (Validation.IsNull(col.RefCols)) continue;

                        if (col.RefCols.IndexOf(',') > 0)
                        {
                            string[] rs = col.RefCols.Split(',');
                            foreach (string item in rs)
                            {
                                refCols.Add(item, col.Name);
                            }
                        }
                        else
                        {
                            refCols.Add(col.RefCols, col.Name);
                        }
                    }
                }


                if (null == refCols) break;

                tb = new Hashtable();

                foreach (KeyValuePair<string, string> ritem in refCols)
                {
                    tb[ritem.Key] = Validation.ToString(row.Cells[ritem.Value].Value);
                }

                if (null == tbList)
                {
                    tbList = new List<Hashtable>();
                }

                tbList.Add(tb);
            }

            this.Close();
        }

        public List<Hashtable> GetSelectedData()
        {
            return tbList;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="status">status null反选，true全选 false反选</param>
        private void ChooseRow(bool? status)
        {
            bool tagIsEmpty = false;
            foreach (DataGridViewRow row in this.dgvMain.Rows)
            {
                tagIsEmpty = Validation.IsNull(row.Tag);

                if (status == null) //反选
                {
                    HighRow(row);
                }
                else if (status == false && tagIsEmpty == false)
                {
                    HighRow(row);
                }
                else if (status == true && tagIsEmpty == true)
                {
                    HighRow(row);
                }
            }
        }

        protected override bool OnPageIndexChanging()
        {
            bool isSelectedItem = false;

            foreach (DataGridViewRow row in this.dgvMain.Rows)
            {
                if (!Validation.IsNull(row.Tag))
                {
                    isSelectedItem = true;
                    break;
                }
            }

            //如果当前有行选中，那么给出提示
            if (isSelectedItem &&
                MessageBox.Show("换页会导致当前选中行被清空，是否继续？", "提示", MessageBoxButtons.YesNo)
                == DialogResult.No)
            {
                return false;
            }

            return true;
        }

        private string classTmpWhere = string.Empty;

        private void ClearTreeSelect(bool isRefreshData)
        {
            this.dgvMain.Select();
            this.dgvMain.Focus();
            classTmpWhere = string.Empty;

            if (isRefreshData)
            {
                BindGrid();
            }
        }

        protected override void OnGridKeyDown(KeyEventArgs e)
        {
            if (isMutiSelect == false || this.dgvMain.CurrentRow == null || this.dgvMain.CurrentRow.Index < 0) return;
            if (e.KeyCode == Keys.Space)
            {
                DataGridViewRow row = this.dgvMain.CurrentRow;

                HighRow(row);
            }
        }

        private void HighRow(DataGridViewRow row)
        {
            if (null == row) return;

            if (Validation.ToString(row.Tag) != "S") //未选中
            {
                row.Tag = "S";
                row.DefaultCellStyle = selectedStyle;
            }
            else //取消选择 
            {
                row.Tag = null;
                row.DefaultCellStyle = nomalStyle;
            }
        }

        protected override void FormKeyDown(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F9)
            {
                tspF9.PerformClick();
            }
            else if (e.KeyCode == Keys.F10)
            {
                tspAll.PerformClick();
            }
            else if (e.KeyCode == Keys.F11)
            {
                tspUnAll.PerformClick();
            }
            else if (e.KeyCode == Keys.F12)
            {
                tspF.PerformClick();
            }
            else if (e.KeyCode == Keys.F5)
            {
                tspSave.PerformClick();
            }
        }

        protected override void AdvanceQueryClick(object sender)
        {
            CheckBox chk = sender as CheckBox;
            if (chk == null) return;
            int heightOfUp = this.tspTop.Height; //高级查询栏离页面顶端的距离，工具栏 + 窗口顶端

            if (_showAdvance == false) //当前状态为显示高级查询栏
            {
                chk.BackColor = Color.FromArgb(22, 94, 173);
                chk.ForeColor = Color.White;

                this.sitemMain.Visible = true;
                this.sitemMain.Location = new Point(0, heightOfUp);

                this.dgvMain.Anchor = AnchorStyles.None;//AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left;
                this.dgvMain.Location = new Point(0, heightOfUp + this.sitemMain.Height);
                this.dgvMain.Height = this.Height - this.tspTop.Height - this.winpg.Height - this.sitemMain.Height - heightOfUp - 6;
            }
            else//当前状态为隐藏高级查询栏
            {
                chk.BackColor = Color.Transparent;
                chk.ForeColor = Color.Black;

                this.dgvMain.Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top;
                this.dgvMain.Location = new Point(0, heightOfUp);
                this.sitemMain.Visible = false;
                this.dgvMain.Height = this.Height - this.tspTop.Height - this.winpg.Height - heightOfUp - 6;
            }

            _showAdvance = !_showAdvance;
        }
    }
}
